<template>
  <div class="report-form">
    <div class="report-form-content">
      <div class="report-form-content-title">
        <h1 style="font-weight: bold" v-if="oper === 'add'">新增初始合同</h1>
        <h1 style="font-weight: bold" v-if="oper === 'edit'">修改初始合同</h1>
        <h1 style="font-weight: bold" v-if="oper === 'view'">查看初始合同</h1>
        <h1 style="font-weight: bold" v-if="oper === 'change'">变更初始合同</h1>
      </div>
      <div style="text-align: right;" v-if="oper === 'add' || oper === 'edit' || oper === 'change'">
        <div class="tabs-list">
          <el-button type="success" @click="handleSave()">
            <svg-icon icon-class="save" />
            保存
          </el-button>
          <el-button v-show="checkAuthCode('')" type="primary" @click="handleSubmit()" v-if="obj.id">
            <svg-icon icon-class="submit" />
            提交审批
          </el-button>
        </div>
      </div>
      <div>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本信息录入" name="1"></el-tab-pane>
          <el-tab-pane label="验收条件" name="2" v-if="obj.needInspection === '1'"></el-tab-pane>
          <el-tab-pane label="收付信息" name="3" v-if="catalog === '1' || catalog === '2'"></el-tab-pane>
          <el-tab-pane label="附件上传" name="4"></el-tab-pane>
        </el-tabs>
        <div class="tabs-list" v-show="activeName === '1'">
          <el-row :gutter="20">
            <div class="tabs-list-head">
              <span>基本信息</span>
            </div>
            <el-col :sm="24" :lg="24" style="padding-left: 20px">
              <el-form class="my-form"
                       ref="objFormRef"
                       :model="obj"
                       :rules="rules"
                       label-position="right" label-width="auto" label-suffix="："
                       :disabled="oper === 'view'">
                <el-card class="update-log">
                  <div class="report-form-list-content">
                    <el-form-item label="合同编号" prop="code">
                      <el-input v-model="obj.code" placeholder="合同编号" />
                    </el-form-item>
                    <el-form-item label="合同名称" prop="name">
                      <el-input v-model="obj.name" placeholder="合同名称" />
                    </el-form-item>
                    <el-form-item label="合同类型" prop="type">
                      <el-select v-model="obj.type" placeholder="请选择" clearable filterable @change="contractTypeChange">
                        <el-option v-for="item in contractTypeList" :key="item.id" :label="`${item.code} - ${item.name} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="合同签订人" prop="contractSignerId">
                      <ContractSigner v-model="obj.contractSignerId" keyName="id" keyShow="name" placeholder="合同签订人" title="合同签订人查询" />
                    </el-form-item>
                    <el-form-item label="合同签订部门" prop="contractSignerDepartmentId">
                      <Organization v-model="obj.contractSignerDepartmentId" keyName="id" keyShow="organizationName" placeholder="合同签订部门" title="部门查询" />
                    </el-form-item>
                    <el-form-item label="负责人" prop="userId">
                      <User v-model="obj.userId" keyName="id" keyShow="name" placeholder="负责人" title="用户查询" />
                    </el-form-item>
                    <el-form-item label="负责部门" prop="departmentId">
                      <Organization v-model="obj.departmentId" keyName="id" keyShow="organizationName" placeholder="负责部门" title="部门查询" />
                    </el-form-item>
                    <el-form-item label="合同金额" prop="amount">
                      <el-input-number v-model="obj.amount" placeholder="请输入合同金额" />
                    </el-form-item>
                    <el-form-item label="合同起始时间" prop="contractLaunch">
                      <el-date-picker v-model="obj.contractLaunch" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="合同终止时间" prop="contractComplete">
                      <el-date-picker v-model="obj.contractComplete" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="是否需要验收" prop="needInspection" @change="changeNeedInspection">
                      <el-radio-group v-model="obj.needInspection">
                        <el-radio-button v-for="item in getEnumList('CommonYesNo')" :label="item.key" :key="item.key">{{item.value}}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </div>
                </el-card>
              </el-form>
            </el-col>
          </el-row>
          <el-form class="my-form"
              ref="objParticipationFormRef"
              :model="partyobj"
              :rules="rulesParticipation"
              label-position="right"
              label-width="auto"
              label-suffix="："
              :disabled="oper === 'view'">
            <el-row :gutter="20">
              <div class="tabs-list-head">
                <span>甲方信息</span>
                <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem(partyobj.partyAList, emptyParticipationsA)">新增</el-button>
              </div>
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log" v-for="(item,index) in partyobj.partyAList" :key="index">
                  <div class="report-form-list-content">
                    <el-form-item label="参与方类型" :prop="'partyAList.' + index + '.participationUserType'" :rules="rulesParticipation.participationUserType">
                      <el-radio-group v-model="item.participationUserType">
                        <el-radio-button v-for="item in getDictList('ContractParticipationUserType')" :key="item.key" :label="item.key">{{ `${item.key} - ${item.value}` }}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="单位/个人名称" :prop="'partyAList.' + index + '.name'" :rules="rulesParticipation.name">
                      <el-input v-model="item.name" placeholder="单位/个人名称" />
                    </el-form-item>
                    <el-form-item label="纳税识别号" :prop="'partyAList.' + index + '.identification'" :rules="rulesParticipation.identification">
                      <el-input v-model="item.identification" placeholder="纳税识别号" />
                    </el-form-item>
                    <el-form-item label="联系人" :prop="'partyAList.' + index + '.contact'" :rules="rulesParticipation.contact">
                      <el-input v-model="item.contact" placeholder="联系人" />
                    </el-form-item>
                    <el-form-item label="联系手机号" :prop="'partyAList.' + index + '.contactMobile'" :rules="rulesParticipation.contactMobile">
                      <el-input v-model="item.contactMobile" placeholder="联系手机号" />
                    </el-form-item>
                    <el-form-item label="收款账号" :prop="'partyAList.' + index + '.proceedsAccount'" :rules="rulesParticipation.proceedsAccount">
                      <el-input v-model="item.proceedsAccount" placeholder="收款账号" />
                    </el-form-item>
                    <el-form-item label="收款银行" :prop="'partyAList.' + index + '.proceedsBankId'" :rules="rulesParticipation.proceedsBankId">
                      <el-select v-model="item.proceedsBankId" placeholder="请选择" clearable filterable>
                        <el-option v-for="item in bankList" :key="item.id" :label="`${item.bankCode} - ${item.bankName} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                      </el-select>
                    </el-form-item>
                  </div>
                  <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(partyobj.partyAList, index)">删除</el-button>
                </el-card>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <div class="tabs-list-head">
                <span>乙方信息</span>
                <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem(partyobj.partyBList, emptyParticipationsB)">新增</el-button>
              </div>
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log" v-for="(item,index) in partyobj.partyBList" :key="index">
                  <div class="report-form-list-content">
                    <el-form-item label="参与方类型" :prop="'partyBList.' + index + '.participationUserType'" :rules="rulesParticipation.participationUserType">
                      <el-radio-group v-model="item.participationUserType">
                        <el-radio-button v-for="item in getDictList('ContractParticipationUserType')" :key="item.key" :label="item.key">{{ `${item.key} - ${item.value}` }}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="单位/个人名称" :prop="'partyBList.' + index + '.name'" :rules="rulesParticipation.name">
                      <el-input v-model="item.name" placeholder="单位/个人名称" />
                    </el-form-item>
                    <el-form-item label="纳税识别号" :prop="'partyBList.' + index + '.identification'" :rules="rulesParticipation.identification">
                      <el-input v-model="item.identification" placeholder="纳税识别号" />
                    </el-form-item>
                    <el-form-item label="联系人" :prop="'partyBList.' + index + '.contact'" :rules="rulesParticipation.contact">
                      <el-input v-model="item.contact" placeholder="联系人" />
                    </el-form-item>
                    <el-form-item label="联系手机号" :prop="'partyBList.' + index + '.contactMobile'" :rules="rulesParticipation.contactMobile">
                      <el-input v-model="item.contactMobile" placeholder="联系手机号" />
                    </el-form-item>
                    <el-form-item label="收款账号" :prop="'partyBList.' + index + '.proceedsAccount'" :rules="rulesParticipation.proceedsAccount">
                      <el-input v-model="item.proceedsAccount" placeholder="收款账号" />
                    </el-form-item>
                    <el-form-item label="收款银行" :prop="'partyBList.' + index + '.proceedsBankId'" :rules="rulesParticipation.proceedsBankId">
                      <el-select v-model="item.proceedsBankId" placeholder="请选择" clearable filterable>
                        <el-option v-for="item in bankList" :key="item.id" :label="`${item.bankCode} - ${item.bankName} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                      </el-select>
                    </el-form-item>
                  </div>
                  <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(partyobj.partyBList, index)">删除</el-button>
                </el-card>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <div class="tabs-list-head">
                <span>第三方信息</span>
                <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem(partyobj.partyCList, emptyParticipationsC)">新增</el-button>
              </div>
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log" v-for="(item,index) in partyobj.partyCList" :key="index">
                  <div class="report-form-list-content">
                    <el-form-item label="参与方类型" :prop="'partyCList.' + index + '.participationUserType'" :rules="rulesParticipation.participationUserType">
                      <el-radio-group v-model="item.participationUserType">
                        <el-radio-button v-for="item in getDictList('ContractParticipationUserType')" :key="item.key" :label="item.key">{{ `${item.key} - ${item.value}` }}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                    <el-form-item label="单位/个人名称" :prop="'partyCList.' + index + '.name'" :rules="rulesParticipation.name">
                      <el-input v-model="item.name" placeholder="单位/个人名称" />
                    </el-form-item>
                    <el-form-item label="纳税识别号" :prop="'partyCList.' + index + '.identification'" :rules="rulesParticipation.identification">
                      <el-input v-model="item.identification" placeholder="纳税识别号" />
                    </el-form-item>
                    <el-form-item label="联系人" :prop="'partyCList.' + index + '.contact'" :rules="rulesParticipation.contact">
                      <el-input v-model="item.contact" placeholder="联系人" />
                    </el-form-item>
                    <el-form-item label="联系手机号" :prop="'partyCList.' + index + '.contactMobile'" :rules="rulesParticipation.contactMobile">
                      <el-input v-model="item.contactMobile" placeholder="联系手机号" />
                    </el-form-item>
                    <el-form-item label="收款账号" :prop="'partyCList.' + index + '.proceedsAccount'" :rules="rulesParticipation.proceedsAccount">
                      <el-input v-model="item.proceedsAccount" placeholder="收款账号" />
                    </el-form-item>
                    <el-form-item label="收款银行" :prop="'partyCList.' + index + '.proceedsBankId'" :rules="rulesParticipation.proceedsBankId">
                      <el-select v-model="item.proceedsBankId" placeholder="请选择" clearable filterable>
                        <el-option v-for="item in bankList" :key="item.id" :label="`${item.bankCode} - ${item.bankName} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                      </el-select>
                    </el-form-item>
                  </div>
                  <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 0" @click="removeItem(partyobj.partyCList, index)">删除</el-button>
                </el-card>
              </el-col>
            </el-row>
            <el-divider />
            <el-row :gutter="20">
              <div class="tabs-list-head tabs-list-head-1">
                <span>合同信息</span>
              </div>
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-form-item label="合同模版" prop="contractTemplateId">
                  <el-select v-model="partyobj.contractTemplateId" placeholder="请选择" clearable filterable @change="contractTemplateChange">
                    <el-option v-for="item in contractTemplateList" :key="item.id" :label="`${item.code} - ${item.name} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                  </el-select>
                </el-form-item>
                <el-form-item label="合同内容" prop="content">
                  <editor v-model="partyobj.content" v-model:readOnly="readOnly" :height="800" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="tabs-list" v-show="activeName === '2'"  v-if="obj.needInspection === '1'">
          <el-row :gutter="20">
            <div>
              <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem(inspectionsObj.inspectionsList, emptyInspections)">新增</el-button>
            </div>
            <el-col :sm="24" :lg="24" style="padding-left: 20px">
              <el-form :model="inspectionsObj" ref="objInspectionFormRef" :rules="rulesInspection"
                label-position="right" label-width="auto" label-suffix="："
                :disabled="oper === 'view'">
                <el-card class="update-log" v-for="(item,index) in inspectionsObj.inspectionsList" :key="index">
                  <div class="report-form-list-content">
                    <el-form-item label="合同验收负责人" :prop="'inspectionsList.' + index + '.principalUserId'" :rules="rulesInspection.principalUserId">
                      <el-select v-model="item.principalUserId" placeholder="请选择" clearable filterable>
                        <el-option v-for="item1 in userList" :key="item1.id" :label="`${item1.name} ${item1.state === '0' ? '【已禁用】' : ''}`" :value="item1.id" :disabled="item1.state === '0'" />
                      </el-select>
                    </el-form-item>
                  </div>
                  <div class="report-form-list-content-1">
                    <el-form-item label="验收内容" :prop="'inspectionsList.' + index + '.content'" :rules="rulesInspection.content">
                      <el-input v-model="item.content" :autosize="{ minRows: 3, maxRows: 8}" type="textarea" class="textarea-1" />
                    </el-form-item>
                  </div>
                  <div class="report-form-list-content-1">
                    <el-form-item label="备注" :prop="'inspectionsList.' + index + '.remark'" :rules="rulesInspection.remark">
                      <el-input v-model="item.remark" :autosize="{ minRows: 5, maxRows: 8}" type="textarea" class="textarea-1" />
                    </el-form-item>
                  </div>
                  <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(inspectionsObj.inspectionsList, index)">删除</el-button>
                </el-card>
              </el-form>
            </el-col>
          </el-row>
        </div>
        <div class="tabs-list" v-show="activeName === '3' && (catalog === '1' || catalog === '2')">
          <div class="catalog" v-if="!catalog || catalog === '3'">
            <span class="hint-text" v-if="!catalog">请选择合同类型！</span>
            <span class="hint-text" v-if="catalog === '3'">合同类型不支持收付！</span>
          </div>
          <el-row :gutter="20" v-if="catalog === '1'">
            <div class="tabs-list-head">
              <span>收款计划</span>
              <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem(payeeObj.payeesList, emptyPayees)">新增</el-button>
            </div>
            <el-col :sm="24" :lg="24" style="padding-left: 20px">
              <el-form :model="payeeObj" ref="objPayeeFormRef" :rules="rulesPayee"
                  label-position="right" label-width="auto" label-suffix="："
                  :disabled="oper === 'view'">
                <el-card class="update-log" v-for="(item,index) in payeeObj.payeesList" :key="index">
                  <div class="report-form-list-content">
                    <el-form-item label="收款批次号" :prop="'payeesList.' + index + '.batchNo'" :rules="rulesPayee.batchNo">
                      <el-input v-model="item.batchNo" placeholder="收款批次" />
                    </el-form-item>
                    <el-form-item label="收款条件" :prop="'payeesList.' + index + '.condition'" :rules="rulesPayee.condition">
                      <el-input v-model="item.condition" placeholder="收款条件" />
                    </el-form-item>
                    <el-form-item label="约定收款金额" :prop="'payeesList.' + index + '.amount'" :rules="rulesPayee.amount">
                      <el-input-number v-model="item.amount" placeholder="约定收款金额" />
                    </el-form-item>
                    <el-form-item label="金额占比" :prop="'payeesList.' + index + '.amountRate'" :rules="rulesPayee.amountRate">
                      <el-input-number v-model="item.amountRate" placeholder="金额占比" style="width: 120px;" />%
                    </el-form-item>
                    <el-form-item label="预计收款日期" :prop="'payeesList.' + index + '.payTime'" :rules="rulesPayee.payTime">
                      <el-date-picker v-model="item.payTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="付款单位" :prop="'payeesList.' + index + '.payCompany'" :rules="rulesPayee.payCompany">
                      <el-input v-model="item.payCompany" placeholder="付款单位" />
                    </el-form-item>
                  </div>
                  <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(payeeObj.payeesList, index)">删除</el-button>
                </el-card>
              </el-form>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="catalog === '2'">
            <div class="tabs-list-head">
              <span>付款计划</span>
              <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem(payObj.paysList, emptyPays)">新增</el-button>
            </div>
            <el-col :sm="24" :lg="24" style="padding-left: 20px">
              <el-form :model="payObj" ref="objPayFormRef" :rules="rulesPay"
                label-position="right" label-width="auto" label-suffix="："
                :disabled="oper === 'view'">
                <el-card class="update-log" v-for="(item,index) in payObj.paysList" :key="index">
                  <div class="report-form-list-content">
                    <el-form-item label="付款批次号" :prop="'paysList.' + index + '.batchNo'" :rules="rulesPay.batchNo">
                      <el-input v-model="item.batchNo" placeholder="付款批次" />
                    </el-form-item>
                    <el-form-item label="付款条件" :prop="'paysList.' + index + '.condition'" :rules="rulesPay.condition">
                      <el-input v-model="item.condition" placeholder="付款条件" />
                    </el-form-item>
                    <el-form-item label="约定支付金额" :prop="'paysList.' + index + '.amount'" :rules="rulesPay.amount">
                      <el-input-number v-model="item.amount" placeholder="约定支付金额" />
                    </el-form-item>
                    <el-form-item label="金额占比" :prop="'paysList.' + index + '.amountRate'" :rules="rulesPay.amountRate">
                      <el-input-number v-model="item.amountRate" placeholder="金额占比" style="width: 120px;" />%
                    </el-form-item>
                    <el-form-item label="预计付款日期" :prop="'paysList.' + index + '.payeeTime'" :rules="rulesPay.payeeTime">
                      <el-date-picker v-model="item.payeeTime" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="收款单位" :prop="'paysList.' + index + '.payeeCompany'" :rules="rulesPay.payeeCompany">
                      <el-input v-model="item.payeeCompany" placeholder="收款单位" />
                    </el-form-item>
                  </div>
                  <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(payObj.paysList, index)">删除</el-button>
                </el-card>
              </el-form>
            </el-col>
          </el-row>
        </div>
        <div class="tabs-list" v-show="activeName === '4'">
          <el-form class="my-form" ref="obj111" :model="obj" :rules="rules"
                   label-position="right" label-width="auto" :disabled="oper === 'view'">
            <!-- 附件信息 -->
            <div class="file-list-btn">
              <span class="file-list-btn-span">*温馨提示:保存成功后才能预览word文档和Excel报表</span>
              <div class="file-list-btns">
                <FileUpload :isShowTip="false" v-model="oFiles" :isShowFileList="false" @uploadedSuccess="uploadedSuccessFn" />
              </div>
            </div>
            <el-table :data="oFiles"
                      style="width: 100%; margin-top: 20px"
                      row-key="id"
                      border
                      default-expand-all
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column label="附件类型">
                <template v-slot="{row}">
                  <el-form-item prop="fileType">
                    <el-select v-model="row.fileType" placeholder="请选择" clearable filterable>
                      <el-option v-for="item in contractFiletypeList" :key="item.id" :label="`${item.code} - ${item.name} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="original" label="附件名称" />
              <el-table-column align="center" label="操作" width="160px" fixed="right">
                <template #default="scope">
                  <el-button type="primary" link @click="downloadFile1(scope.row)">下载</el-button>
                  <el-button type="primary" link @click="viewFile1(scope.row)">预览</el-button>
                  <el-button type="danger" link @click="removeFile1(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
    </div>
    <el-dialog v-model="attachmentVisible" title="附件预览" width="70%" top="2vh">
      <attachmentPreview v-model:attachmentId="previewAttachmentId" />
      <div style="text-align:right;">
        <el-button type="danger" @click="attachmentVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'3001'" :businessId="obj.id" @doSubmit="doSubmit" />
    <!--
    <el-dialog v-model="selectAttachmentVisible" title="选择附件" width="70%" top="2vh">
      <selectAttachmentMultiple :isVisible="selectAttachmentVisible" @selectAttachment="selectAttachmentFn" @close="selectAttachmentVisible = false"></selectAttachmentMultiple>
    </el-dialog>
    -->
  </div>
</template>
<script setup>
import {ref, getCurrentInstance} from 'vue'
import {doGet, doPost, doDownload} from '@/config/http'
import {
  svc,
  notifySuccess,
  getListPageSize,
  customValidator,
  getEnumList,
  alertErrorMsg,
  getDictList, checkAuthCode
} from "@/config/common";
//import selectAttachmentMultiple from '@/views/components/base/selectAttachmentMultiple.vue'
import attachmentPreview from '@/views/components/base/attachmentPreview.vue'
import { useRoute, useRouter } from 'vue-router'
import SvgIcon from "@/components/SvgIcon/index.vue";
import selectApprove from "@/views/components/base/selectApprove.vue";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import ContractSigner from "@/views/components/contract/selectContractSigner.vue";
import initListStore from '@/store/modules/initList'

const router = useRouter()
const route = useRoute()

const { proxy: ctx } = getCurrentInstance();

let dialogApproveVisible = ref(false)
let objFormRef = ref(null)
let objParticipationFormRef = ref(null)
let objInspectionFormRef = ref(null)
let objPayeeFormRef = ref(null)
let objPayFormRef = ref(null)
let approveIdObjFormRef = ref(null)

let id = ref('')
let oper = ref(route.query.oper)
let payeeObj = ref({
  payeesList: [] // 收款计划
})
let payObj = ref({
  paysList: [] // 付款计划
})

let obj = ref({
  kind: '1',
  amount: null, // 合同金额
  code: '', // 合同编码
  contractComplete: '', // 	合同终止时间
  contractLaunch: '', // 合同起止时间
  contractSignerId: '', // 合同签订人ID
  departmentId: '', // 负责部门ID
  id: '', //	主键ID
  name: '', // 合同名称
  needInspection: '', // 是否需要验收
  contractSignerDepartmentId: '', // 合同签订部门ID
  state: '', // 合同状态
  type: '', // 合同类型
  userId: '', // 负责人用户ID
})

let partyobj = ref({
  partyAList: [],
  partyBList: [],
  partyCList: [],
  content: '', // 合同内容
  contractTemplateId: '', // 合同模板ID
})

let oFiles = ref([])
let catalog = ref('')

let previewAttachmentId = ref('')
let attachmentVisible = ref(false)

// 验收条件
const emptyInspections = {
  content: '', // 	验收内容
  contractInitialId: '', // 合同ID
  id: '', // 主键Id
  remark: '', // 备注
}

// 	初始合同收款信息
const emptyPayees = {
  amount: null, // 约定收款金额
  amountRate: null, // 金额占比
  batchNo: '', // 收款批次号
  condition: '', // 收款条件
  contractInitialId: '', // 合同ID
  id: '', // 主键Id
  payCompany: '', // 	付款单位
  payTime: '', // 预计收款时间
}

// 	初始合同付款信息
const emptyPays = {
  amount: null, // 约定付款金额
  amountRate: null, // 金额占比
  batchNo: '', // 付款批次号
  condition: '', // 付款条件
  contractInitialId: '', // 合同ID
  id: '', // 主键Id
  payeeCompany: '', // 收款单位
  payeeTime: '', // 	预计付款时间
}

// 初始合同甲方
const emptyParticipationsA = {
  contact: '', // 联系人
  contactIdcard: '', // 	联系人证件号码
  contactMobile: '', // 联系手机号
  contractInitialId: '', // 	合同ID
  id: '', // 主键ID
  identification: '', // 纳税识别号
  name: '', // 名称
  participationType: '0', // 参与类型
  participationUserType: null, // 参与方类型
  proceedsAccount: '', // 收款账号
  proceedsBankId: '', // 收款银行ID
}
// 初始合同乙方
const emptyParticipationsB = {
  contact: '', // 联系人
  contactIdcard: '', // 	联系人证件号码
  contactMobile: '', // 联系手机号
  contractInitialId: '', // 	合同ID
  id: '', // 主键ID
  identification: '', // 纳税识别号
  name: '', // 名称
  participationType: '1', // 参与类型
  participationUserType: null, // 参与方类型
  proceedsAccount: '', // 收款账号
  proceedsBankId: '', // 收款银行ID
}
// 初始合同第三方
const emptyParticipationsC = {
  contact: '', // 联系人
  contactIdcard: '', // 	联系人证件号码
  contactMobile: '', // 联系手机号
  contractInitialId: '', // 	合同ID
  id: '', // 主键ID
  identification: '', // 纳税识别号
  name: '', // 名称
  participationType: '2', // 参与类型
  participationUserType: null, // 参与方类型
  proceedsAccount: '', // 收款账号
  proceedsBankId: '', // 收款银行ID
}
let inspectionsObj = ref({
  inspectionsList: [] // 初始合同验收条件
})
partyobj.value.partyAList = [Object.assign({}, emptyParticipationsA)] // 甲方
partyobj.value.partyBList = [Object.assign({}, emptyParticipationsB)] // 乙方
partyobj.value.partyCList = [] // 第三方

let approveList = ref([])

const rules = {
  code: [{ required: false, validator: customValidator, min: 0, max: 100, label: '合同编码', trigger: ['blur', 'change'] }],
  name: [{ required: true, validator: customValidator, min: 1, max: 200, label: '合同名称', trigger: ['blur', 'change'] }],
  type: [{ required: true, validator: customValidator, min: 0, max: 20, label: '合同类型', trigger: ['blur', 'change'] }],
  contractSignerId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '合同签订人ID', trigger: ['blur', 'change'] }],
  contractSignerDepartmentId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '合同签订部门ID', trigger: ['blur', 'change'] }],
  departmentId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '负责部门ID', trigger: ['blur', 'change'] }],
  userId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '负责人用户ID', trigger: ['blur', 'change'] }],
  amount: [{ required: true, validator: customValidator, min: 0, max: 13, label: '合同金额', trigger: ['blur', 'change'] }],
  contractLaunch: [{ required: true, validator: customValidator, min: 0, max: 20, label: '合同起始时间', trigger: ['blur', 'change'] }],
  contractComplete: [{ required: true, validator: customValidator, min: 0, max: 20, label: '合同终止时间', trigger: ['blur', 'change'] }],
  needInspection: [{ required: true, validator: customValidator, min: 0, max: 20, label: '是否需要验收', trigger: ['blur', 'change'] }],
  state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同状态', trigger: ['blur', 'change'] }],
}

const rulesParticipation = {
  contractInitialId: [{ required: false, validator: customValidator, min: 1, max: 20, label: '合同ID', trigger: ['blur', 'change'] }],
  participationType: [{ required: true, validator: customValidator, min: 1, max: 20, label: '参与类型', trigger: ['blur', 'change'] }],
  participationUserType: [{ required: true, validator: customValidator, min: 0, max: 20, label: '参与方类型', trigger: ['blur', 'change'] }],
  name: [{ required: false, validator: customValidator, min: 0, max: 200, label: '名称', trigger: ['blur', 'change'] }],
  identification: [{ required: false, validator: customValidator, min: 0, max: 200, label: '纳税识别号', trigger: ['blur', 'change'] }],
  contact: [{ required: false, validator: customValidator, min: 0, max: 20, label: '联系人', trigger: ['blur', 'change'] }],
  contactIdcard: [{ required: false, validator: customValidator, min: 0, max: 20, label: '联系人证件号码', trigger: ['blur', 'change'] }],
  contactMobile: [{ required: false, validator: customValidator, min: 0, max: 20, label: '联系手机号', trigger: ['blur', 'change'] }],
  proceedsBankId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '收款银行ID', trigger: ['blur', 'change'] }],
  proceedsAccount: [{ required: false, validator: customValidator, min: 0, max: 100, label: '收款账号', trigger: ['blur', 'change'] }],
  contractTemplateId: [{ required: false, validator: customValidator, min: 0, max: 20, label: '合同模版ID', trigger: ['blur', 'change'] }],
  content: [{ required: true, validator: customValidator, label: '合同内容', trigger: ['blur', 'change'] }],
}

const rulesInspection = {
  principalUserId: [{ required: true, validator: customValidator, min: 0, max: 20, label: '验收条件负责人', trigger: ['blur', 'change'] }],
  content: [{ required: true, validator: customValidator, min: 0, max: 1000, label: '验收内容', trigger: ['blur', 'change'] }],
  remark: [{ required: false, validator: customValidator, min: 0, max: 3000, label: '备注', trigger: ['blur', 'change'] }],
}

const rulesPayee = {
  batchNo: [{ required: true, validator: customValidator, min: 0, max: 200, label: '收款批次号', trigger: ['blur', 'change'] }],
  condition: [{ required: true, validator: customValidator, min: 0, max: 1000, label: '收款条件', trigger: ['blur', 'change'] }],
  amount: [{ required: true, validator: customValidator, min: 0, max: 13, label: '约定收款金额', trigger: ['blur', 'change'] }],
  amountRate: [{ required: true, validator: customValidator, min: 0, max: 13, label: '金额占比', trigger: ['blur', 'change'] }],
  payTime: [{ required: false, validator: customValidator, min: 0, max: 20, label: '预计收款时间', trigger: ['blur', 'change'] }],
  payCompany: [{ required: true, validator: customValidator, min: 0, max: 200, label: '付款单位', trigger: ['blur', 'change'] }],
}

const rulesPay = {
  batchNo: [{ required: true, validator: customValidator, min: 0, max: 200, label: '付款批次号', trigger: ['blur', 'change'] }],
  condition: [{ required: true, validator: customValidator, min: 0, max: 1000, label: '付款条件', trigger: ['blur', 'change'] }],
  amount: [{ required: true, validator: customValidator, min: 0, max: 13, label: '约定收款金额', trigger: ['blur', 'change'] }],
  amountRate: [{ required: true, validator: customValidator, min: 0, max: 13, label: '金额占比', trigger: ['blur', 'change'] }],
  payeeTime: [{ required: false, validator: customValidator, min: 0, max: 20, label: '预计付款时间', trigger: ['blur', 'change'] }],
  payeeCompany: [{ required: true, validator: customValidator, min: 0, max: 200, label: '收款单位', trigger: ['blur', 'change'] }],
}

let activeName = ref('1')
let readOnly = ref(oper.value === 'view')

const handleSelectionChange = (val) => {
  console.debug('handleSelectionChange', val)
}

let contractTypeList = initListStore().contractTypeList // 合同类型
// let contractCooperationList = ref([]) // 往来单位
// let contractFeetypeList = ref([]) // 合同费用类型
let contractTemplateList = initListStore().contractTemplateList // 合同模版
let bankList = initListStore().bankList // 银行
let userList = initListStore().userList // 用户
// let governmentList = ref([]) //  政府单位
// let organizationList = ref([]) // 部门
// let contractSignerList = ref([]) // 签订人
let contractFiletypeList = initListStore().contractFiletypeList // 合同附件类型
// const initList = async () => {
//   let p1 = doGet(svc, '/contract-type/page', {pageSize: getListPageSize()}, false) // 合同类型
//   let p2 = doGet(svc, '/contract-cooperation/page', {pageSize: getListPageSize()}, false) // 往来单位
//   let p3 = doGet(svc, '/contract-feetype/page', {pageSize: getListPageSize()}, false) // 合同费用类型
//   let p4 = doGet(svc, '/contract-template/page', {pageSize: getListPageSize()}, false) // 合同模版
//   let p5 = doGet(svc, '/bank/page', {pageSize: getListPageSize()}, false) // 银行
//   let p6 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false) // 用户
//   let p7 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false) //  政府单位
//   let p8 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false) // 部门
//   let p9 = doGet(svc, '/contract-signer/page', {pageSize: getListPageSize()}, false) // 签订人
//   let p10 = doGet(svc, '/contract-filetype/page', {pageSize: getListPageSize()}, false) // 合同附件类型
//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8, p9, p10])
//   contractTypeList.value = resArray[0]['records']
//   contractCooperationList.value = resArray[1]['records']
//   contractFeetypeList.value = resArray[2]['records']
//   contractTemplateList.value = resArray[3]['records']
//   bankList.value = resArray[4]['records']
//   userList.value = resArray[5]['records']
//   governmentList.value = resArray[6]['records']
//   organizationList.value = resArray[7]['records']
//   contractSignerList.value = resArray[8]['records']
//   contractFiletypeList.value = resArray[9]['records']
//   initObj()
// }

const initObj = async () => {
  oper.value = route.query.oper
  id.value = null
  if (route.query.id) {
    id.value = route.query.id
    obj.value = await doGet(svc, '/contract-initial/' + id.value, {}, true)
    let index = contractTypeList.value.findIndex(item => item.id === obj.value.type)
    catalog.value = contractTypeList.value[index].catalog
    partyobj.value.content = obj.value.content
    partyobj.value.contractTemplateId = obj.value.contractTemplateId

    // 验收条件
    let inspectionsList1 = await doGet(svc, '/contract-initial-inspection/listByField', {field: 'contractInitialId', values: id.value}, false)
    // 合同收款信息
    let payeesList1 = await doGet(svc, '/contract-initial-payee/listByField', {field: 'contractInitialId', values: id.value}, false)
    // 合同付款信息
    let paysList1 = await doGet(svc, '/contract-initial-pay/listByField', {field: 'contractInitialId', values: id.value}, false)
    // 参与方信息
    let participationsList1 = await doGet(svc, '/contract-initial-participation/listByField', {field: 'contractInitialId', values: id.value}, false)
    // 附件信息
    let oFiles1 = await doGet(svc, '/contract-initial-file/listByField', {field: 'contractInitialId', values: id.value}, false)
    console.debug('oFiles1', oFiles1)
    oFiles.value = oFiles1.map(item => {
      item.original = item.attachmentName
      item.fileType = item.attachmentType
      return item
    })
    if (inspectionsList1.length > 0) {
      inspectionsObj.value.inspectionsList = inspectionsList1
    }
    if (payeesList1.length > 0) {
      payeeObj.value.payeesList = payeesList1
    }
    if (paysList1.length > 0) {
      payObj.value.paysList = paysList1
    }

    if (participationsList1.length > 0) {
      let partAList = participationsList1.filter(item => item.participationType === '0')
      let partBList = participationsList1.filter(item => item.participationType === '1')
      let partCList = participationsList1.filter(item => item.participationType === '2')
      if (partAList.length > 0) {
        partyobj.value.partyAList = partAList
      }
      if (partBList.length > 0) {
        partyobj.value.partyBList = partBList
      }
      if (partCList.length > 0) {
        partyobj.value.partyCList = partCList
      }
    }
  }
}

initObj()


const addItem = (arr, obj) => {
  arr.push(Object.assign({}, obj))
}
const removeItem = (arr, index) => {
  arr.splice(index, 1)
}

const selectAttachmentFn = (list) => {
  console.debug('list-------------',list)
  if (list.length > 0) {
    list.forEach(item => {
      item.original = item.fileName
      item.size = item.fileSize
      oFiles.value.push(item)
    })
  }
  console.debug('oFiles.value',oFiles.value)
  oFiles.value = Array.from(new Set(oFiles.value))
}

const contractTemplateChange = (val) => {
  let index = contractTemplateList.value.findIndex(item => item.id === val)
  partyobj.value.content = contractTemplateList.value[index].content
}

const contractTypeChange = (val) => {
  console.log('val------------',val)
  let index = contractTypeList.value.findIndex(item => item.id === val)
  catalog.value = contractTypeList.value[index].catalog
  console.log('catalog.value',catalog.value)
  if (catalog.value === '1') {
    payObj.value.paysList = []
    payeeObj.value.payeesList = [Object.assign({}, emptyPayees)]
  } else if (catalog.value === '2') {
    payeeObj.value.payeesList = []
    payObj.value.paysList = [Object.assign({}, emptyPays)]
  } else {
    payObj.value.paysList = []
    payeeObj.value.payeesList = []
  }
}

const uploadedSuccessFn = (file) => {
  oFiles.value.push(file)
}

const buildObj = () => {
  obj.value.inspections = inspectionsObj.value.inspectionsList
  let list = []

  if (partyobj.value.partyAList.length > 0) {
    list = list.concat(partyobj.value.partyAList)
  }
  if (partyobj.value.partyBList.length > 0) {
    list = list.concat(partyobj.value.partyBList)
  }
  if (partyobj.value.partyCList.length > 0) {
    list = list.concat(partyobj.value.partyCList)
  }

  obj.value.content = partyobj.value.content
  obj.value.contractTemplateId = partyobj.value.contractTemplateId
  obj.value.participations = list
  obj.value.payees = payeeObj.value.payeesList
  obj.value.pays = payObj.value.paysList
  obj.value.files = []
  if (oFiles.value.length > 0) {
    obj.value.files = oFiles.value.map(item => {
      if (obj.value.id) {
        return {
          attachmentId: item.id,
          attachmentName: item.original,
          attachmentType: item.fileType,
          expenditureReimbursementId: obj.value.id
        }
      } else {
        return {
          attachmentId: item.id,
          attachmentName: item.original,
          attachmentType: item.fileType
        }
      }
    })
  }
  return obj.value
}

const downloadFile1 = (row) => {
  console.log('row',row)
  if (row.attachmentId) {
    doDownload(svc, `/customAttachment/download/${row.attachmentId}`, {})
  } else {
    doDownload(svc, `/customAttachment/download/${row.id}`, {})
  }
}
const viewFile1 = (row) => {
  attachmentVisible.value = true
  setTimeout(() => {
    if (row.attachmentId) {
      previewAttachmentId.value = row.attachmentId
    } else {
      previewAttachmentId.value = row.id
    }
  },100)
}
const removeFile1 = (scope) => {
  oFiles.value.splice(scope.$index, 1)
}

async function checkForm(callback) {
  let valid1 = await objFormRef.value.validate().catch((err)=>{return err}) // 基础信息
  let valid2 = await objParticipationFormRef.value.validate().catch((err)=>{return err}) // 参与方信息以及合同模版，合同内容
  if (valid1 !== true || valid2 !== true) {
    console.log('23333')
    alertErrorMsg("合同基本信息表单验证不通过，请检查")
    return
  }

  // 验收
  if (obj.value.needInspection === '1') {
    let valid3 = await objInspectionFormRef.value.validate().catch((err)=>{return err}) // 验收
    if (valid3 !== true) {
      alertErrorMsg("验收信息表单验证不通过，请检查")
      return
    }
  }

  // 收款信息
  if (catalog.value === '1') {
    let valid4 = await objPayeeFormRef.value.validate().catch((err)=>{return err}) // 收款
    if (valid4 !== true) {
      alertErrorMsg("收款信息表单验证不通过，请检查")
      return
    }
  }

  // 付款信息
  if (catalog.value === '2') {
    let valid5 = await objPayFormRef.value.validate().catch((err)=>{return err}) // 付款
    if (valid5 !== true) {
      alertErrorMsg("付款信息表单验证不通过，请检查")
      return
    }
  }

  if (callback)callback()
}

const handleSave = () => {
  checkForm(() => {
    let o = buildObj()
    doPost(svc, '/customContractInitial/saveContractInitial', o, true).then(() => {
      notifySuccess('保存成功')
      ctx.goTargetByName('contractInitial', {})
    })
  })
}
const handleSubmit = () => {
  checkForm(() => {
    let o = buildObj()
    doPost(svc, '/customContractInitial/saveContractInitial', o, false).then(res => {
      obj.value.id = res['id']
      obj.value.version = res['version']
      dialogApproveVisible.value = true
    })
  })
}
const doSubmit = async (data) => {
  await checkForm(() => {
    let o = buildObj()
    o.approveId = data.approveId
    o.approveNodes = data.approveNodes
    doPost(svc, '/customContractInitial/submitContractInitial', o, true).then(() => {
      notifySuccess('提交成功')
      ctx.goTargetByName('contractInitial', {})
    })
  })
}

function changeNeedInspection() {
  inspectionsObj.value.inspectionsList = []
  if (obj.value.needInspection === '1') {
    inspectionsObj.value.inspectionsList.push(Object.assign({}, emptyInspections))
  }
}
</script>
<style scoped>
td,th {
  padding: 20px 0;
}
.report-form {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: #fff;
  z-index: 10;
  padding: 20px;
  overflow-x: hidden;
  overflow-y: auto;
}
.report-form-content {
  padding: 20px;
}
.report-form-content-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.file-list-btn {
  display: flex;
  align-items: center;
  justify-content: space-between
}
.file-list-btns {
  display: flex;
  align-items: center;
}
.file-list-btn-span {
  color: #F56C6C;
  font-size: 12px;
}
.tabs-list-head {
  padding-left: 20px;
  display: flex;
  align-items: center;
}
.tabs-list-head span {
  font-size: 18px;
  color: #303133;
  font-weight: bold;
}
.tabs-list-head-1 {
  margin-bottom: 30px;
}
.catalog {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.hint-text {
  padding-top: 200px;
  font-size: 20px;
  font-weight: bold;
  color: #F56C6C;
}
</style>
